using AutoMapper;
using MediatR;
using SqlSugar;
using TaskProject.Application.Command.Plan;
using TaskProject.Domain.Plan;
using TaskProject.ErrorCode;
using TaskProject.Extension.Plan;
using TaskProject.InfrasIntructure.Implement;

namespace TaskProject.Application.Handler.Plan
{
    /// <summary>
    /// 根据主键查询生产计划处理器
    /// </summary>
    public class GetProductionPlanByIdHandler : IRequestHandler<GetProductionPlanByIdCommand, APIResult<ProductionPlanDTO>>
    {
        private readonly DatabaseContext _db;
        private readonly IMapper _mapper;

        public GetProductionPlanByIdHandler(DatabaseContext db, IMapper mapper)
        {
            _db = db;
            _mapper = mapper;
        }

        public async Task<APIResult<ProductionPlanDTO>> Handle(GetProductionPlanByIdCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<ProductionPlanDTO>();

            try
            {
                // 根据主键查询生产计划
                var productionPlan = await _db.sqlSugar.Queryable<ProductionPlanModel>()
                    .Where(p => p.PlanId == request.PlanId && !p.IsDel)
                    .FirstAsync(cancellationToken);

                if (productionPlan == null)
                {
                    result.Code = APIEnum.Fail;
                    result.Msg = "生产计划不存在";
                    return result;
                }

                // 转换为DTO
                var planDto = _mapper.Map<ProductionPlanDTO>(productionPlan);

                // 查询生产物品
                var items = await _db.sqlSugar.Queryable<ProductionPlanItemModel>()
                    .Where(i => i.PlanId == productionPlan.PlanId)
                    .OrderBy(i => i.SortOrder)
                    .ToListAsync(cancellationToken);

                planDto.ProductionItems = _mapper.Map<List<ProductionPlanItemDTO>>(items);

                // 查询附件
                var attachments = await _db.sqlSugar.Queryable<ProductionPlanAttachmentModel>()
                    .Where(a => a.PlanId == productionPlan.PlanId)
                    .OrderByDescending(a => a.UploadDate)
                    .ToListAsync(cancellationToken);

                planDto.Attachments = _mapper.Map<List<ProductionPlanAttachmentDTO>>(attachments);

                result.Code = APIEnum.Success;
                result.Msg = "查询成功";
                result.Data = planDto;
            }
            catch (Exception ex)
            {
                result.Code = APIEnum.Fail;
                result.Msg = $"查询失败：{ex.Message}";
            }

            return result;
        }
    }
}